﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DCT.CodeBox.LightLog.Codes.Formatter
{
    public static class LogStringFormatter
    {

        static LogStringFormatter()
        {
        }

        public static string Render(object obj)
        {
            if (obj == null)
            {
                return "";
            }

            ILogStringFormatter formatter = null;

            if (obj is IConvertible)
            {
                formatter = CreateSingleton<ToStringLogFormatter>();
            }
            else if (obj is IDictionary<string, object>)
            {
                formatter = CreateSingleton<DictionaryFormatter>();
            }
            else {
                formatter = CreateSingleton<ObjectFormatter>();
            }

            return formatter.Render(obj);
        }

        private static Dictionary<Type, ILogStringFormatter> mapper = new Dictionary<Type, ILogStringFormatter>();

        private static ILogStringFormatter CreateSingleton<T>()
            where T : class,ILogStringFormatter, new()
        {
            Type type = typeof(T);
            if (!mapper.ContainsKey(type))
            {
                mapper[type] = new T();
            }
            return mapper[type];
        }
    }
}
